/**
 * 聊天模块路由文件
 * 包含所有API接口和Socket.IO实时通信处理
 */

const express = require('express');
const socketIo = require('socket.io');
const lhxChatService = require('../services/lhx_chat_service');
const { generateRoomId, parseRoomId, isUserInRoom } = require('../utils/lhx_room_helper');

// LHX聊天模块 - 图片上传相关依赖
const multer = require('multer');
const { lhxCosClient, lhxCosConfig } = require('../config/lhx_cos');

// LHX聊天模块 - TRTC音视频通话相关依赖
const { lhxTrtcConfig, lhxGenerateUserSig, lhxGenerateRoomId } = require('../config/lhx_trtc');

const router = express.Router();

// LHX聊天模块 - multer配置（用于图片上传）
const lhxUpload = multer({ 
  storage: multer.memoryStorage(),
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB限制
  fileFilter: (req, file, cb) => {
    // 只允许图片格式
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只能上传图片文件'), false);
    }
  }
});

// LHX聊天模块 - multer配置（用于语音上传）
const lhxVoiceUpload = multer({ 
  storage: multer.memoryStorage(),
  limits: { fileSize: 10 * 1024 * 1024 }, // 10MB限制
  fileFilter: (req, file, cb) => {
    // 只允许音频格式
    if (file.mimetype.startsWith('audio/')) {
      cb(null, true);
    } else {
      cb(new Error('只能上传音频文件'), false);
    }
  }
});

// ==================== API 路由 ====================

// 1. 患者端接口

/**
 * 获取患者可聊天的医生列表
 * GET /lhx/patient/:patientId/doctors
 */
router.get('/patient/:patientId/doctors', async (req, res) => {
  try {
    const { patientId } = req.params;
    
    // 验证患者权限
    const isValid = await lhxChatService.validateUserPermission(patientId, 'patient');
    if (!isValid) {
      return res.status(403).json({
        success: false,
        message: '患者不存在或无权限'
      });
    }
    
    // 获取医生列表
    const doctors = await lhxChatService.getPatientDoctorList(patientId);
    
    res.json({
      success: true,
      data: doctors,
      message: '获取医生列表成功'
    });
    
  } catch (error) {
    console.error('获取患者医生列表失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取医生列表失败'
    });
  }
});

// 2. 医生端接口

/**
 * 获取医生的聊天患者列表
 * GET /lhx/doctor/:doctorId/patients
 */
router.get('/doctor/:doctorId/patients', async (req, res) => {
  try {
    const { doctorId } = req.params;
    
    // 验证医生权限
    const isValid = await lhxChatService.validateUserPermission(doctorId, 'doctor');
    if (!isValid) {
      return res.status(403).json({
        success: false,
        message: '医生不存在或无权限'
      });
    }
    
    // 获取患者聊天列表
    const chats = await lhxChatService.getDoctorChatList(doctorId);
    
    res.json({
      success: true,
      data: chats,
      message: '获取聊天列表成功'
    });
    
  } catch (error) {
    console.error('获取医生聊天列表失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取聊天列表失败'
    });
  }
});

/**
 * 获取患者的聊天医生列表
 * GET /lhx/patient/:patientId/chats
 */
router.get('/patient/:patientId/chats', async (req, res) => {
  try {
    const { patientId } = req.params;
    
    // 验证患者权限
    const isValid = await lhxChatService.validateUserPermission(patientId, 'patient');
    if (!isValid) {
      return res.status(403).json({
        success: false,
        message: '患者不存在或无权限'
      });
    }
    
    // 获取医生聊天列表
    const chats = await lhxChatService.getPatientChatList(patientId);
    
    res.json({
      success: true,
      data: chats,
      message: '获取聊天列表成功'
    });
    
  } catch (error) {
    console.error('获取患者聊天列表失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取聊天列表失败'
    });
  }
});

/**
 * 获取患者可以聊天的医生列表
 * GET /lhx/patient/:patientId/available-doctors
 */
router.get('/patient/:patientId/available-doctors', async (req, res) => {
  try {
    const { patientId } = req.params;
    
    // 验证患者权限
    const isValid = await lhxChatService.validateUserPermission(patientId, 'patient');
    if (!isValid) {
      return res.status(403).json({
        success: false,
        message: '患者不存在或无权限'
      });
    }
    
    // 获取可聊天的医生列表
    const doctors = await lhxChatService.getAvailableDoctorsForPatient(patientId);
    
    res.json({
      success: true,
      data: doctors,
      message: '获取可聊天医生列表成功'
    });
    
  } catch (error) {
    console.error('获取可聊天医生列表失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取医生列表失败'
    });
  }
});

// 3. 通用接口

/**
 * 获取聊天历史记录
 * GET /lhx/messages/:roomId?page=1&limit=50
 */
router.get('/messages/:roomId', async (req, res) => {
  try {
    const { roomId } = req.params;
    const { page = 1, limit = 50, userId, userType } = req.query;
    
    // 验证房间ID格式
    try {
      parseRoomId(roomId);
    } catch (error) {
      return res.status(400).json({
        success: false,
        message: '房间ID格式错误'
      });
    }
    
    // 验证用户权限（如果提供了用户信息）
    if (userId && userType) {
      const hasPermission = await lhxChatService.validateUserPermission(userId, userType, roomId);
      if (!hasPermission) {
        return res.status(403).json({
          success: false,
          message: '无权限查看此聊天记录'
        });
      }
    }
    
    // 获取聊天记录
    const result = await lhxChatService.getChatHistory(roomId, parseInt(page), parseInt(limit));
    
    res.json({
      success: true,
      data: result.messages,
      pagination: result.pagination,
      message: '获取聊天记录成功'
    });
    
  } catch (error) {
    console.error('获取聊天记录失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取聊天记录失败'
    });
  }
});

/**
 * 创建聊天房间（患者发起）
 * POST /lhx/room/create
 */
router.post('/room/create', async (req, res) => {
  try {
    const { patientId, doctorId, firstMessage } = req.body;
    
    // 参数验证
    if (!patientId || !doctorId || !firstMessage) {
      return res.status(400).json({
        success: false,
        message: '参数不完整：需要patientId、doctorId、firstMessage'
      });
    }
    
    // 创建聊天房间和发送第一条消息
    const result = await lhxChatService.createChatRoom(patientId, doctorId, firstMessage);
    
    res.json({
      success: true,
      data: result,
      message: '聊天房间创建成功'
    });
    
  } catch (error) {
    console.error('创建聊天房间失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '创建聊天房间失败'
    });
  }
});

/**
 * 标记消息为已读
 * POST /lhx/messages/:roomId/read
 */
router.post('/messages/:roomId/read', async (req, res) => {
  try {
    const { roomId } = req.params;
    const { userId, userType } = req.body;
    
    // 参数验证
    if (!userId || !userType) {
      return res.status(400).json({
        success: false,
        message: '参数不完整：需要userId、userType'
      });
    }
    
    // 验证权限
    const hasPermission = await lhxChatService.validateUserPermission(userId, userType, roomId);
    if (!hasPermission) {
      return res.status(403).json({
        success: false,
        message: '无权限操作此房间'
      });
    }
    
    // 标记已读
    const count = await lhxChatService.markMessagesAsRead(roomId, userId, userType);
    
    res.json({
      success: true,
      data: { readCount: count },
      message: '消息已标记为已读'
    });
    
  } catch (error) {
    console.error('标记消息已读失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '标记消息已读失败'
    });
  }
});

/**
 * 获取用户信息
 * GET /lhx/user/:userId
 */
router.get('/user/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    
    const user = await lhxChatService.getUserInfo(userId);
    
    res.json({
      success: true,
      data: user,
      message: '获取用户信息成功'
    });
    
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取用户信息失败'
    });
  }
});



/**
 * 患者发起新聊天
 * POST /lhx/patient/:patientId/start-chat
 */
router.post('/patient/:patientId/start-chat', async (req, res) => {
  try {
    const { patientId } = req.params;
    const { doctorId, firstMessage } = req.body;
    
    // 参数验证
    if (!doctorId || !firstMessage) {
      return res.status(400).json({
        success: false,
        message: '参数不完整：需要doctorId、firstMessage'
      });
    }
    
    // 验证患者权限
    const isValid = await lhxChatService.validateUserPermission(patientId, 'patient');
    if (!isValid) {
      return res.status(403).json({
        success: false,
        message: '患者不存在或无权限'
      });
    }
    
    // 发起新聊天
    const result = await lhxChatService.startNewChatWithDoctor(patientId, doctorId, firstMessage);
    
    res.json({
      success: true,
      data: result,
      message: result.isNewChat ? '新聊天创建成功' : '消息发送成功'
    });
    
  } catch (error) {
    console.error('患者发起聊天失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '发起聊天失败'
    });
  }
});

/**
 * LHX聊天模块 - 图片上传接口
 * POST /lhx/upload-image
 */
router.post('/upload-image', lhxUpload.single('image'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ 
        success: false, 
        message: '没有上传文件' 
      });
    }
    
    // 生成唯一文件名
    const timestamp = Date.now();
    const randomStr = Math.random().toString(36).substr(2, 9);
    const fileExt = req.file.originalname.split('.').pop() || 'jpg';
    const lhxImageKey = `lhx-chat-images/${timestamp}-${randomStr}.${fileExt}`;
    
    // 上传到腾讯云COS
    const lhxUploadResult = await lhxCosClient.putObject({
      Bucket: lhxCosConfig.bucket,
      Region: lhxCosConfig.region,
      Key: lhxImageKey,
      Body: req.file.buffer,
      ContentType: req.file.mimetype
    });
    
    // 生成图片访问URL
    const lhxImageUrl = `${lhxCosConfig.baseUrl}/${lhxImageKey}`;
    
    console.log(`[LHX-CHAT] 图片上传成功: ${lhxImageKey}`);
    
    res.json({ 
      success: true, 
      imageUrl: lhxImageUrl,
      filename: lhxImageKey,
      message: '图片上传成功'
    });
  } catch (error) {
    console.error('[LHX-CHAT] 图片上传失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '图片上传失败' 
    });
  }
});

/**
 * LHX聊天模块 - 语音上传接口
 * POST /lhx/upload-voice
 */
router.post('/upload-voice', lhxVoiceUpload.single('voice'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ 
        success: false, 
        message: '没有上传语音文件' 
      });
    }
    
    // 生成唯一文件名
    const timestamp = Date.now();
    const randomStr = Math.random().toString(36).substr(2, 9);
    const fileExt = req.file.originalname.split('.').pop() || 'webm';
    const lhxVoiceKey = `lhx-voice/${timestamp}-${randomStr}.${fileExt}`;
    
    // 上传到腾讯云COS
    const lhxUploadResult = await lhxCosClient.putObject({
      Bucket: lhxCosConfig.bucket,
      Region: lhxCosConfig.region,
      Key: lhxVoiceKey,
      Body: req.file.buffer,
      ContentType: req.file.mimetype
    });
    
    // 生成语音访问URL
    const lhxVoiceUrl = `${lhxCosConfig.baseUrl}/${lhxVoiceKey}`;
    
    console.log(`[LHX-CHAT] 语音上传成功: ${lhxVoiceKey}`);
    
    res.json({ 
      success: true, 
      voiceUrl: lhxVoiceUrl,
      filename: lhxVoiceKey,
      fileSize: req.file.size,
      message: '语音上传成功'
    });
  } catch (error) {
    console.error('[LHX-CHAT] 语音上传失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '语音上传失败' 
    });
  }
});

/**
 * LHX聊天模块 - 生成基于用户的TRTC房间ID
 * @param {string} userId - 用户ID
 * @returns {number} 1-4294967294范围内的房间ID
 */
function lhxGenerateTrtcRoomId(userId) {
  let hash = 0;
  const str = userId + Date.now().toString().slice(-6); // 添加时间戳后6位确保唯一性
  for (let i = 0; i < str.length; i++) {
    hash = ((hash << 5) - hash + str.charCodeAt(i)) & 0x7fffffff;
  }
  return (hash % 4294967293) + 1; // 确保在1-4294967294范围内
}

/**
 * LHX聊天模块 - 获取TRTC配置信息
 * POST /lhx/get-trtc-config
 */
router.post('/get-trtc-config', async (req, res) => {
  try {
    const { userId, roomId } = req.body;
    
    if (!userId) {
      return res.status(400).json({ 
        success: false, 
        message: '用户ID不能为空' 
      });
    }
    
    // 生成UserSig
    const userSig = lhxGenerateUserSig(userId);
    
    // LHX聊天模块 - 生成有效的TRTC房间ID（1-4294967294范围内）
    const trtcRoomId = roomId || lhxGenerateTrtcRoomId(userId);
    
    console.log(`[LHX-TRTC] 生成TRTC配置: userId=${userId}, roomId=${trtcRoomId}`);
    
    res.json({ 
      success: true, 
      data: {
        sdkAppId: lhxTrtcConfig.sdkAppId,
        userId: userId,
        userSig: userSig,
        roomId: trtcRoomId
      },
      message: 'TRTC配置获取成功'
    });
  } catch (error) {
    console.error('[LHX-TRTC] TRTC配置获取失败:', error);
    res.status(500).json({ 
      success: false, 
      message: 'TRTC配置获取失败' 
    });
  }
});

// ==================== Socket.IO 实时通信 ====================

/**
 * 初始化Socket.IO聊天功能
 * @param {Object} server - HTTP服务器实例
 * @returns {Object} Socket.IO实例
 */
function initializeLhxChat(server) {
  const io = socketIo(server, {
    cors: {
      origin: "*",
      methods: ["GET", "POST"],
      credentials: true
    },
    // 连接配置
    pingTimeout: 60000,
    pingInterval: 25000
  });

  // 存储在线用户信息
  const onlineUsers = new Map();

  /**
   * 处理Socket连接
   */
  io.on('connection', (socket) => {
    console.log(`[LHX-CHAT] 用户连接: ${socket.id}`);

    /**
     * 用户加入聊天房间
     * 数据格式: { patientId, doctorId, userType, userId }
     */
    socket.on('lhx_join_room', async (data) => {
      try {
        const { patientId, doctorId, userType, userId } = data;
        
        // 参数验证
        if (!patientId || !doctorId || !userType || !userId) {
          socket.emit('lhx_error', { message: '参数不完整' });
          return;
        }

        // 生成房间ID
        const roomId = generateRoomId(patientId, doctorId);
        
        // 验证用户权限
        const hasPermission = await lhxChatService.validateUserPermission(userId, userType, roomId);
        if (!hasPermission) {
          socket.emit('lhx_error', { message: '无聊天权限或用户不存在' });
          return;
        }
        
        // 如果是患者，额外验证是否有就诊记录
        if (userType === 'patient') {
          const chatPermission = await lhxChatService.validateChatPermission(patientId, doctorId);
          if (!chatPermission) {
            socket.emit('lhx_error', { message: '无聊天权限，请先完成就诊' });
            return;
          }
        }

        // 加入房间
        socket.join(roomId);
        
        // 存储Socket信息
        socket.lhxRoomId = roomId;
        socket.lhxUserId = userId;
        socket.lhxUserType = userType;
        
        // 记录在线用户
        onlineUsers.set(socket.id, {
          userId,
          userType,
          roomId,
          joinTime: new Date()
        });

        console.log(`[LHX-CHAT] ${userType} ${userId} 加入房间: ${roomId}`);
        
        // 获取并发送历史消息
        try {
          const history = await lhxChatService.getChatHistory(roomId, 1, 500);
          socket.emit('lhx_history_messages', {
            messages: history.messages,
            pagination: history.pagination
          });
        } catch (error) {
          console.error('获取历史消息失败:', error);
          socket.emit('lhx_error', { message: '获取历史消息失败' });
        }
        
        // 通知房间内其他用户有新用户加入
        socket.to(roomId).emit('lhx_user_joined', {
          userId,
          userType,
          joinTime: new Date()
        });
        
        // 标记消息为已读
        try {
          await lhxChatService.markMessagesAsRead(roomId, userId, userType);
        } catch (error) {
          console.error('标记消息已读失败:', error);
        }

      } catch (error) {
        console.error('[LHX-CHAT] 加入房间失败:', error);
        socket.emit('lhx_error', { message: '加入房间失败' });
      }
    });

    /**
     * 处理发送消息
     * 数据格式: { content, messageType }
     */
    socket.on('lhx_send_message', async (messageData) => {
      try {
        // 验证Socket状态
        if (!socket.lhxRoomId || !socket.lhxUserId || !socket.lhxUserType) {
          socket.emit('lhx_error', { message: '请先加入房间' });
          return;
        }

        const { content, messageType = 'text', fileInfo = null } = messageData;
        
        // LHX聊天模块 - 内容验证（图片和语音消息允许空内容）
        if (messageType === 'text' && (!content || content.trim().length === 0)) {
          socket.emit('lhx_error', { message: '消息内容不能为空' });
          return;
        }

        // 发送消息
        const message = await lhxChatService.sendMessage({
          roomId: socket.lhxRoomId,
          senderId: socket.lhxUserId,
          senderType: socket.lhxUserType,
          content: content ? content.trim() : '', // LHX聊天模块 - 处理空内容
          messageType,
          fileInfo
        });

        console.log(`[LHX-CHAT] 消息发送: ${socket.lhxUserType} ${socket.lhxUserId} -> ${socket.lhxRoomId}`);
        
        // 向房间内所有用户广播消息
        io.to(socket.lhxRoomId).emit('lhx_receive_message', {
          _id: message._id,
          roomId: message.roomId,
          senderId: message.senderId,
          senderType: message.senderType,
          content: message.content,
          messageType: message.messageType,
          timestamp: message.timestamp,
          status: message.status,
          ...(message.fileInfo && { fileInfo: message.fileInfo })
        });

      } catch (error) {
        console.error('[LHX-CHAT] 发送消息失败:', error);
        socket.emit('lhx_error', { message: error.message || '消息发送失败' });
      }
    });

    /**
     * 处理消息已读状态
     */
    socket.on('lhx_mark_read', async () => {
      try {
        if (!socket.lhxRoomId || !socket.lhxUserId || !socket.lhxUserType) {
          return;
        }

        await lhxChatService.markMessagesAsRead(
          socket.lhxRoomId, 
          socket.lhxUserId, 
          socket.lhxUserType
        );

        // 通知房间内其他用户消息已读
        socket.to(socket.lhxRoomId).emit('lhx_messages_read', {
          userId: socket.lhxUserId,
          userType: socket.lhxUserType,
          readTime: new Date()
        });

      } catch (error) {
        console.error('[LHX-CHAT] 标记已读失败:', error);
      }
    });

    /**
     * 处理正在输入状态
     */
    socket.on('lhx_typing', (data) => {
      if (!socket.lhxRoomId) return;
      
      socket.to(socket.lhxRoomId).emit('lhx_user_typing', {
        userId: socket.lhxUserId,
        userType: socket.lhxUserType,
        isTyping: data.isTyping
      });
    });

    // ==================== LHX聊天模块 - 音视频通话信令处理 ====================

    /**
     * 发起通话邀请
     * 数据格式: { callType: 'audio'|'video', trtcRoomId }
     */
    socket.on('lhx_call_invite', (data) => {
      try {
        if (!socket.lhxRoomId || !socket.lhxUserId) {
          socket.emit('lhx_error', { message: '请先加入聊天房间' });
          return;
        }

        const { callType, trtcRoomId } = data;
        if (!callType || !trtcRoomId) {
          socket.emit('lhx_error', { message: '通话参数不完整' });
          return;
        }

        console.log(`[LHX-TRTC] 用户${socket.lhxUserId}发起${callType}通话邀请, TRTC房间:${trtcRoomId}`);

        // 向房间内其他用户发送通话邀请
        socket.to(socket.lhxRoomId).emit('lhx_call_invitation', {
          fromUserId: socket.lhxUserId,
          fromUserType: socket.lhxUserType,
          callType: callType,
          trtcRoomId: trtcRoomId,
          timestamp: Date.now()
        });

      } catch (error) {
        console.error('[LHX-TRTC] 发起通话邀请失败:', error);
        socket.emit('lhx_error', { message: '发起通话失败' });
      }
    });

    /**
     * 接受通话邀请
     * 数据格式: { trtcRoomId }
     */
    socket.on('lhx_call_accept', (data) => {
      try {
        const { trtcRoomId } = data;
        if (!trtcRoomId) {
          socket.emit('lhx_error', { message: '通话房间ID不能为空' });
          return;
        }

        console.log(`[LHX-TRTC] 用户${socket.lhxUserId}接受通话, TRTC房间:${trtcRoomId}`);

        // 通知发起方通话被接受
        socket.to(socket.lhxRoomId).emit('lhx_call_accepted', {
          fromUserId: socket.lhxUserId,
          fromUserType: socket.lhxUserType,
          trtcRoomId: trtcRoomId,
          timestamp: Date.now()
        });

      } catch (error) {
        console.error('[LHX-TRTC] 接受通话失败:', error);
        socket.emit('lhx_error', { message: '接受通话失败' });
      }
    });

    /**
     * 拒绝通话邀请
     * 数据格式: { trtcRoomId, reason }
     */
    socket.on('lhx_call_reject', (data) => {
      try {
        const { trtcRoomId, reason = 'rejected' } = data;

        console.log(`[LHX-TRTC] 用户${socket.lhxUserId}拒绝通话, 原因:${reason}`);

        // 通知发起方通话被拒绝
        socket.to(socket.lhxRoomId).emit('lhx_call_rejected', {
          fromUserId: socket.lhxUserId,
          fromUserType: socket.lhxUserType,
          trtcRoomId: trtcRoomId,
          reason: reason,
          timestamp: Date.now()
        });

      } catch (error) {
        console.error('[LHX-TRTC] 拒绝通话失败:', error);
      }
    });

    /**
     * 取消通话邀请
     * 数据格式: { trtcRoomId }
     */
    socket.on('lhx_call_cancel', (data) => {
      try {
        const { trtcRoomId } = data;

        console.log(`[LHX-TRTC] 用户${socket.lhxUserId}取消通话`);

        // 通知对方通话被取消
        socket.to(socket.lhxRoomId).emit('lhx_call_cancelled', {
          fromUserId: socket.lhxUserId,
          fromUserType: socket.lhxUserType,
          trtcRoomId: trtcRoomId,
          timestamp: Date.now()
        });

      } catch (error) {
        console.error('[LHX-TRTC] 取消通话失败:', error);
      }
    });

    /**
     * 结束通话
     * 数据格式: { trtcRoomId, duration }
     */
    socket.on('lhx_call_end', (data) => {
      try {
        const { trtcRoomId, duration = 0 } = data;

        console.log(`[LHX-TRTC] 用户${socket.lhxUserId}结束通话, 时长:${duration}秒`);

        // 通知对方通话结束
        socket.to(socket.lhxRoomId).emit('lhx_call_ended', {
          fromUserId: socket.lhxUserId,
          fromUserType: socket.lhxUserType,
          trtcRoomId: trtcRoomId,
          duration: duration,
          timestamp: Date.now()
        });

      } catch (error) {
        console.error('[LHX-TRTC] 结束通话失败:', error);
      }
    });

    /**
     * 监听聊天房间（用于列表页面）
     * 数据格式: { patientId, doctorId, userType, userId, isListPage }
     */
    socket.on('lhx_monitor_room', async (data) => {
      try {
        const { patientId, doctorId, userType, userId, isListPage } = data;
        
        // 参数验证
        if (!patientId || !doctorId || !userType || !userId) {
          socket.emit('lhx_error', { message: '监听房间参数不完整' });
          return;
        }

        // 生成房间ID
        const roomId = generateRoomId(patientId, doctorId);
        
        // 验证用户权限
        const hasPermission = await lhxChatService.validateUserPermission(userId, userType, roomId);
        if (!hasPermission) {
          socket.emit('lhx_error', { message: '无权限监听此房间' });
          return;
        }
        
        // 加入房间以监听消息
        socket.join(roomId);
        
        console.log(`[LHX-CHAT] ${userType} ${userId} 开始监听房间: ${roomId} (列表页面: ${isListPage})`);
        
        // 如果是列表页面监听，不发送历史消息，也不存储为活跃聊天
        if (isListPage) {
          // 可以选择性地发送一个确认消息
          socket.emit('lhx_room_monitored', { roomId, status: 'monitoring' });
        }
        
      } catch (error) {
        console.error('[LHX-CHAT] 监听房间失败:', error);
        socket.emit('lhx_error', { message: '监听房间失败' });
      }
    });

    /**
     * 处理断开连接
     */
    socket.on('disconnect', () => {
      console.log(`[LHX-CHAT] 用户断开连接: ${socket.id}`);
      
      // 清理在线用户记录
      const userInfo = onlineUsers.get(socket.id);
      if (userInfo) {
        onlineUsers.delete(socket.id);
        
        // 通知房间内其他用户有用户离开
        if (socket.lhxRoomId) {
          socket.to(socket.lhxRoomId).emit('lhx_user_left', {
            userId: userInfo.userId,
            userType: userInfo.userType,
            leaveTime: new Date()
          });
        }
      }
    });

    /**
     * 处理连接错误
     */
    socket.on('error', (error) => {
      console.error(`[LHX-CHAT] Socket错误 ${socket.id}:`, error);
      socket.emit('lhx_error', { message: '连接出现错误' });
    });
  });

  // 定期清理过期连接
  setInterval(() => {
    const now = Date.now();
    for (const [socketId, userInfo] of onlineUsers.entries()) {
      if (now - userInfo.joinTime.getTime() > 24 * 60 * 60 * 1000) { // 24小时
        onlineUsers.delete(socketId);
      }
    }
  }, 60 * 60 * 1000); // 每小时清理一次

  console.log('[LHX-CHAT] Socket.IO 聊天服务初始化完成');
  return io;
}

// ==================== 错误处理中间件 ====================

/**
 * 路由错误处理
 */
router.use((err, req, res, next) => {
  console.error('[LHX-CHAT] 路由错误:', err);
  
  res.status(err.status || 500).json({
    success: false,
    message: err.message || '服务器内部错误',
    ...(process.env.NODE_ENV === 'development' && { 
      stack: err.stack,
      details: err 
    })
  });
});

module.exports = {
  router,
  initializeLhxChat
};